package org.dtrd.modules.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dtrd.modules.service.entity.po.DtrdRlServicePackage;
import org.dtrd.modules.service.entity.request.EditServiceRequest;
import org.dtrd.modules.service.mapper.DtrdRlServicePackageMapper;
import org.dtrd.modules.service.service.IDtrdEntRdServicePackageService;
import org.dtrd.modules.service.service.IDtrdRlServicePackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务包和服务套餐的关系 服务实现类
 * </p>
 *
 * @author QR
 * @since 2021-11-19 18:52:54
 */
@DS("multi-datasource1")
@Service
public class DtrdRlServicePackageServiceImpl extends ServiceImpl<DtrdRlServicePackageMapper, DtrdRlServicePackage> implements IDtrdRlServicePackageService {

    @Autowired
    private IDtrdEntRdServicePackageService packageService;

    @Override
    public boolean editServicePackage(Integer packageId, List<EditServiceRequest> servicePackageRelationInfoList) {
        // 删除原来packageId记录
        packageService.clearPackage(packageId);
        // 传入的列表为空不用继续
        if (CollectionUtil.isEmpty(servicePackageRelationInfoList)) {
            return true;
        }
        // 新增传入的数据
        List<DtrdRlServicePackage> newPackageServiceRelations = servicePackageRelationInfoList.stream()
                .map(dto -> new DtrdRlServicePackage(packageId).init().parseFromDTO(dto))
                .collect(Collectors.toList());
        return saveBatch(newPackageServiceRelations);
    }

    @Override
    public void clearPackageRelation(Integer packageId) {
        LambdaQueryWrapper<DtrdRlServicePackage> wrapper = Wrappers.lambdaQuery(DtrdRlServicePackage.class)
                .eq(DtrdRlServicePackage::getPackageId, packageId);
        List<DtrdRlServicePackage> servicePackages = list(wrapper);
        if (CollectionUtil.isNotEmpty(servicePackages)) {
            servicePackages.stream()
                    .map(DtrdRlServicePackage::getPackageId)
                    .forEach(id -> baseMapper.clearServiceMonthAndPeriod(id));
        }
    }

    @Override
    public List<DtrdRlServicePackage> listByPackageId(Integer packageId) {
        LambdaQueryWrapper<DtrdRlServicePackage> wrapper = Wrappers.lambdaQuery(DtrdRlServicePackage.class)
                .eq(DtrdRlServicePackage::getPackageId, packageId);
        return list(wrapper);
    }
}
